//
//  QChooseAddressVC.m
//  QoilPublic
//
//  Created by 杨凯 on 2017/4/24.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "QChooseAddressVC.h"
#import "QChooseAddressCell.h"
#import "QHistoryAddressModel.h"
#import "MJExtension.h"
#import "QMapLocationVC.h"
@interface QChooseAddressVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView * tbView;
@property (nonatomic,strong)NSMutableArray * dataArr;
@property (nonatomic,strong)QHistoryAddressModel * nowModel;//当前位置
@end

@implementation QChooseAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择加油地址";
    [self createUI];
    [self requestData];
    //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(NewAddressNotification) name:@"NewAddressNotifi" object:nil];
}
/*- (void)NewAddressNotifi:(NSNotification *)noti{
    
    NSString *address = [noti.userInfo objectForKey:@"address"];
}*/
- (void)requestData{
    WS(wSelf);
    NSString * url = [QParamService urlWithAction:@"getHistoryAddress"];
    NSDictionary * para = [QParamService getHistoryAddress];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [QViewUtility disMissNoNetWorkInVC:self];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:wSelf.view];
        if (error) {
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:_tbView];
            }
            return ;
        }
        QBaseModel * baseModel = [QBaseModel objectFromDict:dict];
        if ([baseModel.result isEqualToString:@"success"]) {
            self.dataArr = [QHistoryAddressModel mj_objectArrayWithKeyValuesArray:[baseModel.items objectForKey:@"historys"]];
            [_tbView reloadData];
            
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:baseModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

- (void)createUI{
     _nowModel = [[QHistoryAddressModel alloc] init];
    //进来的默认定位
    //**************************************************//
    _nowModel.city = [QUserInfo sharedInfo].cityStr;
    _nowModel.address = [QUserInfo sharedInfo].address;
    _nowModel.limitArea = [QUserInfo sharedInfo].districtStr;
    _nowModel.x = [QUserInfo sharedInfo].lat;
    _nowModel.y = [QUserInfo sharedInfo].lon;
    _nowModel.localString = [NSString stringWithFormat:@"%@%@",[QUserInfo sharedInfo].cityStr,[QUserInfo sharedInfo].districtStr];
    //**************************************************//

    [self.view addSubview:self.tbView];
    [self.tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo (@0);
        make.left.equalTo (@10);
        make.right.equalTo (@-10);
        make.bottom.equalTo (@0);
    }];
    
    [self.tbView registerNib:[UINib nibWithNibName:@"QChooseAddressCell" bundle:nil] forCellReuseIdentifier:@"QChooseAddressCell"];
    self.tbView.showsVerticalScrollIndicator = NO;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 35;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
        header.backgroundColor = tableView.backgroundColor;
        UILabel * lab = [QViewUtility createLabelWithFrame:CGRectMake(10, 10, 200, 20) font:14 textAlignment:0 textColor:[QColorUtility defaultDeepGrayColor] text:@"当前地址"];
        [header addSubview:lab];
        return header;

    }else{
        UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        header.backgroundColor = tableView.backgroundColor;
        UILabel * lab = [QViewUtility createLabelWithFrame:CGRectMake(10, 25, 200, 20) font:14 textAlignment:0 textColor:[QColorUtility defaultDeepGrayColor] text:@"历史地址"];
        
        [header addSubview:lab];
        return header;

    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return _dataArr.count;
    }
}

- (UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QChooseAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QChooseAddressCell" forIndexPath:indexPath];
    cell.backgroundColor = tableView.backgroundColor;
    WS(wSelf);
    if (indexPath.section == 0) {
        cell.locationBtn.hidden = NO;
        cell.model = _nowModel;
        cell.locationAgainBlock = ^{
            QMapLocationVC * vc = [[QMapLocationVC alloc] init];
            vc.block = ^(double lat,double lon,NSString *title,NSString *subTitle,NSString *province){
                
                __strong QChooseAddressVC *sSelf = wSelf;

                sSelf->_nowModel.x = [NSString stringWithFormat:@"%lf",lon];
                sSelf->_nowModel.y = [NSString stringWithFormat:@"%lf",lat];
                sSelf->_nowModel.localString = title;
                NSRange rang = [title rangeOfString:@"市"];
                if(rang.length != 0){
                    sSelf->_nowModel.city = [title substringToIndex:rang.location+1];
                    sSelf->_nowModel.limitArea = [title substringFromIndex:rang.location+1];
                    sSelf->_nowModel.address = subTitle;
                    if(sSelf->_nowModel.limitArea.length == 0){//如果回传过来的没有区，说明用户是搜索第一条，默认选区
                        sSelf->_nowModel.limitArea = subTitle;
                    }
                }

                [_tbView reloadData];
                
            };
            [wSelf.navigationController pushViewController:vc animated:YES];
        };
    }else{
        cell.locationBtn.hidden = YES;
        QHistoryAddressModel * model = [_dataArr objectAtIndex:indexPath.row];
        model.localString =[NSString stringWithFormat:@"%@%@",model.city,model.limitArea];
        model.indexPath = indexPath;
        cell.model = model;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (_nowModel.address == nil) {
            return ;
        }
        self.block(_nowModel);
    }else{
        QHistoryAddressModel * model =[_dataArr objectAtIndex:indexPath.row];
        
        if ([model.address containsString:model.city]) {
            model.address = [model.address stringByReplacingOccurrencesOfString:model.city withString:@""];
        }
        if ([model.address containsString:model.limitArea]) {
            model.address = [model.address stringByReplacingOccurrencesOfString:model.limitArea withString:@""];
        }
        self.block(model);
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (UITableView*)tbView {
    if (!_tbView) {
        _tbView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tbView.dataSource = self;
        _tbView.delegate = self;
        _tbView.backgroundColor = [UIColor clearColor];
        _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tbView;
}

- (void)back
{
    NSLog(@"back");
    QMapLocationVC * vc = [[QMapLocationVC alloc] init];

    vc.block = ^(double lat,double lon,NSString *title,NSString *subTitle,NSString *province){
        
        __strong QChooseAddressVC *sSelf = self;
        
        sSelf->_nowModel.x = [NSString stringWithFormat:@"%lf",lon];
        sSelf->_nowModel.y = [NSString stringWithFormat:@"%lf",lat];
        sSelf->_nowModel.localString = title;
        NSRange rang = [title rangeOfString:@"市"];
        if(rang.length != 0){
            sSelf->_nowModel.city = [title substringToIndex:rang.location+1];
            sSelf->_nowModel.limitArea = [title substringFromIndex:rang.location+1];
            sSelf->_nowModel.address = subTitle;
            if(sSelf->_nowModel.limitArea.length == 0){//如果回传过来的没有区，说明用户是搜索第一条，默认选区
                sSelf->_nowModel.limitArea = subTitle;
            }
        }
        
    };
    self.block(_nowModel);
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
